<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import { YkMenu, YkContent, YkTaskBar, utils } from 'yklib'
import router from './router'
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useToolStore } from './stores/tool'

const {
  isLogin,
  currentUsername,
  currentUserEmail,
  vip,
  money,
  lastLogin,
  lastTickTime,
  accountStatus,
  processing
} = storeToRefs(useToolStore())

declare global {
  interface Window {
    pywebview: any,
    debug: (text: string, type: any) => void
    setTaskBarContent: (text: string, progress: number) => void
  }
}

const save = () => {
  window.pywebview.api.save_note().then((response: string) => {
    alert(response)
  })
}

const options = [{
  label: '文件',
  submenu: [
    {
      label: '打开',
      click: () => {
        router.push('/')
      }
    },
    {
      label: '保存',
      click: () => {
        router.push('/about')
      }
    }
  ]
}]

const user = computed(() => {
  return {
    username: currentUsername.value,
    email: currentUserEmail.value,
    money: money.value,
    vip: vip.value,
    lastLogin: lastLogin.value,
    isLogin: isLogin.value
  }
})

const handleEvent = (buttonId: 'button1' | 'button2') => {
  if (buttonId === 'button1') {
    utils._chargeCoin(currentUsername.value, 'https://sges.yangke.site:20003', 'https://sges.yangke.site:5001')
  } else if (buttonId === 'button2') {
    currentUsername.value = '' as any
    currentUserEmail.value = '' as any
    currentUserEmail.value = 0 as any
    currentUserEmail.value = 0 as any
    lastLogin.value = '' as any
    isLogin.value = false as any
    router.push('./login') // 返回登录页面
  }
}

/**
 * 暴露给python后台调用的接口，用于设置前端界面的任务栏信息
 * @param text
 * @param progress
 */
const setTaskBar = (text: string, progress: number) => {
  taskBarContent.value = text
  taskProgress.value = progress
}

onMounted(() => {
  window.setTaskBarContent = setTaskBar // throttle(appendText, 100)
  router.push('./login')
})

const taskBarContent = ref('')
const taskProgress = ref(0)

const displayProgress = computed(() => {
  /**
   * 当传入的taskProgress值＞0小于100时，任务栏上显示进度条
   */
  return !(taskProgress.value <= 0.01 || taskProgress.value >= 99.99)
})

const display = computed(() => {// 当是登录页面时，菜单和任务栏不显示，否则显示
  return router.currentRoute.value.name !== 'login'
})

let connErrTries = 0
/**
 * 发送心跳信息，用于每天的计费引用
 */
const sendLoginMessage = async () => {
  if (currentUsername.value === '未登录') {
    connErrTries = 0
    return
  }
  const today = new Date()
  const today_str = `${today.getFullYear()}${today.getMonth() + 1}${today.getDate()}`
  if (lastTickTime.value.slice(0, 8) === today_str) { // 如果当天已经systemTick过了，则不在发送心跳
    console.log('already ticked')
  } else {
    const res = await utils.systemTick('https://sges.yangke.site:5001', currentUsername.value)
    if (res.Status === 'Connection Error' || res.Status === 'Server Error') {
      connErrTries += 1
      if (connErrTries >= 10) {
        isLogin.value = false // 服务器连接失败
      }
    } else if (res.Status === 'success' || res.Status === 'arrear') {
      money.value = res.Money
      connErrTries = 0
      lastTickTime.value = today_str
    }
  }
}

const intervalId = setInterval(sendLoginMessage, 60000)
</script>

<template>
  <div>
    <YkMenu v-if="display" button1-text="充值" :user="user" :height="24" @card-event="handleEvent" :options="options"></YkMenu>
    <YkContent class="bg-green-100" :menu-bar-height="24" :task-bar-height="24">
      <RouterView style="max-width: 8000px" />
    </YkContent>
    <YkTaskBar v-if="display" :height="24">
      <div class="w-full grid grid-cols-4 pl-2">
        <div class="col-span-3">
          <span> {{ taskBarContent }} </span>
        </div>
        <div class="col-span-1">
          <meter class="w-full" min="0" max="100" :value="taskProgress" v-if="displayProgress">{{ taskBarContent }}
          </meter>
        </div>
      </div>
    </YkTaskBar>
  </div>
</template>

<style scoped>

</style>
